package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.ui.fragment.TaskListFragment;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TaskListActivity extends BaseActivity {

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager2)
    ViewPager2 mViewPager2;

    private String[] mTitles = new String[]{"待完成", "已完成", "已过期"};
    private Fragment[] mFragments = new Fragment[mTitles.length];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_examination_list;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mViewPager2.setAdapter(new TaskListFragmentAdapter(this, mFragments));
        mViewPager2.setOffscreenPageLimit(mFragments.length - 1);
        TabLayoutMediator mediator = new TabLayoutMediator(mTabLayout, mViewPager2,
                (tab, position) -> tab.setText(mTitles[position]));
        mediator.attach();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.my_task;
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, TaskListActivity.class);
        context.startActivity(intent);
    }

    private static class TaskListFragmentAdapter extends FragmentStateAdapter {

        private Fragment[] mFragments;

        TaskListFragmentAdapter(@NonNull FragmentActivity fragmentActivity, Fragment[] fragments) {
            super(fragmentActivity);
            mFragments = fragments;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            if (mFragments[position] == null) {
                mFragments[position] = TaskListFragment.newInstance(position + 1);
            }
            return mFragments[position];
        }

        @Override
        public int getItemCount() {
            return mFragments.length;
        }
    }
}
